/*****************************************************************************************
**  Author:dgz master
**  Contact：jiduxiong@dagongzao.com
**
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码

import { id } from "element-plus/es/locale/index.mjs";

// import { type } from "os";
// import { Value } from "sass";
// import { json } from "stream/consumers";


let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: "",
    gridBody: "",
    gridFooter: "",
    //新建、编辑弹出框扩展组件
    modelHeader: "",
    modelBody: "",
    modelRight: "",
    modelFooter: ""
  },
  tableAction: "", //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
     //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
        //示例：在按钮的最前面添加一个按钮
        //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
        //     name: "按钮", //按钮名称
        //     icon: "el-icon-document", //按钮图标：https://element.eleme.cn/#/zh-CN/component/icon
        //     type: "primary", //按钮样式:https://element-plus.gitee.io/zh-CN/component/button.html
        //     //color:"#eee",//自定义按钮颜色
        //     onClick: function () {
        //       this.$Message.success("点击了按钮");
        //     }
        //   });
        //示例：设置修改新建、编辑弹出框字段标签的长度
        // this.boxOptions.labelWidth = 150;
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.onClick_ed_up = false
      buttonType: 'primary',
      this.boxButtons.unshift({
        name: "上传MES",
        icon: "el-icon-plus",
        type: "primary",       
        onClick: () =>{
          // this.complete();
          this.up_to_mes()
          console.log("这是品管的页面！！！！！")
        }
      })
      if(this.boxButtons[0].type == "success"){
          this.changeButtonType('primary'); // 橙色
          // //写上传MES的功能，并改变按钮颜色
          // this.changeButtonType('success'); // 绿色
        }
    },
    deal_data(table_name,coun_name){
      if(this.editFormFields[table_name] == ""){
        coun_name += 0
      }else{
        coun_name += parseInt(this.editFormFields[table_name])
      }
      return coun_name
    },
    formatCurrentTime(modle) {
      console.log("时间函数！！！")
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            if(modle == "sql"){
              return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }else{
              return `${year}-${month}-${day}`;
            }
            
        },
    // 修改按钮类型的方法
    changeButtonType(newType) {
      // 找到对应的按钮（假设是第一个按钮）
      const button = this.boxButtons[0];
      if (button) {
        button.type = newType;
        // 强制更新视图（某些情况下可能需要）
        this.$forceUpdate();
      }
    },
    judgment_data(name){
      var data_judge = 0
      if(this.editFormFields[name] == ""){
        data_judge = 0
      }else{
        data_judge = parseInt(this.editFormFields[name])
      }
      return data_judge
    },
    up_to_mes(item) {
      console.log("上传MES系统");
      if (this.editFormFields["lot"] == "") {
        alert("lot信息没有！！！");
        return;
      }else{
        let lot = this.editFormFields["lot"]
        if (this.boxButtons[0].type == "primary") {

          this.changeButtonType('warning'); // 橙色

          // 创建loading实例
          const loadingInstance = this.$loading({
            lock: true,
            text: '数据上传中...',
            spinner: 'el-icon-loading',
            background: 'rgba(247, 237, 237, 0.7)'
          });
          var oder_name = this.editFormFields.order_name
          var blank_lightspot_ = this.judgment_data("light_point")
          var blank_crack_final_qty_ = this.judgment_data("lie_W")
          var blank_dit_final_qty_ = this.judgment_data("sha_yan")
          var blank_silicone_oil_ = this.judgment_data("gui_you")
          var blank_flux_bad_ = this.judgment_data("ct_no")
          var blank_oxygen_ = this.judgment_data("yang_hua")
          var mark_final_qty_ = this.judgment_data("dao_heng")
          var verticality_final_qty_ = this.judgment_data("chuzhi")
          var size_final_qty_ = this.judgment_data("all_chicun")
          var chip_final_qty_ = this.judgment_data("beng_side")
          var chamfer_final_qty_ = this.judgment_data("dao_C")
          var blank_edge_broken_final_qty_ = this.judgment_data("black_side")
          var broken_final_qty_ = this.judgment_data("all_keb")
          var pit_final_qty_ = this.judgment_data("all_mk")
          var sampling_reliability_qty_ = this.judgment_data("song_ce")
          var plating_check_fall_qty_ = this.judgment_data("jb_lost")
          var jb_tjp = this.judgment_data("jb_tjp")
          plating_check_fall_qty_ += jb_tjp
          var defect_plating_bubble_final_qty_ = this.judgment_data("qipao")
          var defect_plating_colordiff_final_qty_ = this.judgment_data("ducengsec")
          var defect_plating_flux_final_qty_ = this.judgment_data("jieheli_no")
          var defect_plating_disability_final_qty_ = this.judgment_data("ducan")
          var defect_plating_concave_pit_final_qty_ = this.judgment_data("aokeng")
          var defect_plating_paint_final_qty_ = this.judgment_data("pengt_jq")
          var defect_plating_net_final_qty_ = this.judgment_data("pengT_zw")
          var defect_plating_foreign_final_qty_ = this.judgment_data("pentu_yw")
          var r_edge_broken_final_qty_ = this.judgment_data("r_kb")
          var pre_edge_broken_final_qty_ = this.judgment_data("qian_kb")
          var suf_edge_broken_final_qty_ = this.judgment_data("hou_kb")
          var rework_test_ = this.judgment_data("kf_ex")
          var rework_colordiff_ = this.judgment_data("kf_ducse")
          var rework_scratch_ = this.judgment_data("kf_duchh")
          var rework_blister_ = this.judgment_data("kf_qipao")
          var rework_outoftol_ = this.judgment_data("kf_cc")
          var rework_edge_broken_ = this.judgment_data("kf_kb")
          var rework_pit_ = this.judgment_data("kf_ak")
          var rework_paint_ = this.judgment_data("kf_jq")
          var rework_foreign_ = this.judgment_data("kf_yw")
          var rework_net_ = this.judgment_data("kf_zw")
          var plating_qualified_fianl_qty_ = this.judgment_data("ok_qty")
          var rework_plating_removed_paint_ = this.judgment_data("kf_dd")

          var pg_backup_2_ = this.editFormFields['backup_2'] //PG

          var c_total = this.judgment_data("c_total")
          var kf_total = this.judgment_data("kf_total")
          
          var wupan = parseFloat(this.editFormFields['wupan'])  //PG
          var lou_jv = parseFloat(this.editFormFields['lou_jv'])  //PG
          var oqc = this.editFormFields['oqc']

          
          var isupmes_time = this.formatCurrentTime("sql")
          this.editFormFields["isupmes_time"] = isupmes_time //无需上传MES
          this.editFormFields["data_time_2"] = isupmes_time //无需上传MES
          
          console.log("blank_lightspot_",blank_lightspot_)

          let time = new Date();
          let year = time.getFullYear();
          let month =time.getMonth() + 1 < 10? "0" + (time.getMonth() + 1): time.getMonth() + 1;
          let date =time.getDate() < 10? "0" + time.getDate(): time.getDate();
          var data_tt = this.formatCurrentTime("up_mes")   //检验时间，需上传MES系统
          console.log("data",data_tt)

          let mes_data = {  
                blank_lightspot: blank_lightspot_,  
                blank_crack_final_qty: blank_crack_final_qty_,  
                blank_dit_final_qty: blank_dit_final_qty_,  
                blank_silicone_oil: blank_silicone_oil_,  
                blank_flux_bad: blank_flux_bad_,  
                blank_oxygen: blank_oxygen_,  
                mark_final_qty: mark_final_qty_,  
                verticality_final_qty: verticality_final_qty_,  
                size_final_qty: size_final_qty_,  
                chip_final_qty: chip_final_qty_,  
                chamfer_final_qty: chamfer_final_qty_,  
                blank_edge_broken_final_qty: blank_edge_broken_final_qty_,  
                broken_final_qty: broken_final_qty_,  
                pit_final_qty: pit_final_qty_,  
                sampling_reliability_qty: sampling_reliability_qty_,  
                plating_check_fall_qty: plating_check_fall_qty_,  
                defect_plating_bubble_final_qty: defect_plating_bubble_final_qty_,  
                defect_plating_colordiff_final_qty: defect_plating_colordiff_final_qty_,  
                defect_plating_flux_final_qty: defect_plating_flux_final_qty_,  
                defect_plating_disability_final_qty: defect_plating_disability_final_qty_,  
                defect_plating_concave_pit_final_qty: defect_plating_concave_pit_final_qty_,  
                defect_plating_paint_final_qty: defect_plating_paint_final_qty_,  
                defect_plating_net_final_qty: defect_plating_net_final_qty_,  
                defect_plating_foreign_final_qty: defect_plating_foreign_final_qty_,  
                r_edge_broken_final_qty: r_edge_broken_final_qty_,  
                pre_edge_broken_final_qty: pre_edge_broken_final_qty_,  
                suf_edge_broken_final_qty: suf_edge_broken_final_qty_,  
                rework_test: rework_test_,  
                rework_colordiff: rework_colordiff_,  
                rework_scratch: rework_scratch_,  
                rework_blister: rework_blister_,  
                rework_outoftol: rework_outoftol_,  
                rework_edge_broken: rework_edge_broken_,  
                rework_pit: rework_pit_,  
                rework_paint: rework_paint_,  
                rework_foreign: rework_foreign_,  
                rework_net: rework_net_,  
                rework_plating_removed_paint: rework_plating_removed_paint_,
                note: pg_backup_2_,
                misjudgment_rate:wupan,
                missed_detection_rate:lou_jv,
                plating_qualified_fianl_qty:plating_qualified_fianl_qty_,
                inspection_time:data_tt,
                judgement:'OK'
            }
            if(broken_final_qty_ == 0){
              mes_data["product_shape_type"] = "big"
            }else{
              mes_data["product_shape_type"] = "small"
            }

            console.log("mes_data",mes_data)
          let jsonString_mes_data = JSON.stringify(mes_data)
          // 网络请求
          new Promise((resolve, reject) => {
            setTimeout(() => {
              // 这里为真实的API调用
              // this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get', {name_order:lot,mes_data:jsonString_mes_data})
              this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get_pg', {name_order:lot,mes_data:jsonString_mes_data})
              .then(res => {
                resolve(res);
                console.log('同步成功:', res);
              })
              .catch(err => {
                reject(err);
              });
            }, 2000); // 这里的setTimeout只是模拟延迟，实际使用时需要移除
          })
          .then(response => {
            // 上传成功处理
            this.$message({
              message: '上传MES成功',
              type: 'success',
              duration: 3000
            });
            this.changeButtonType('success'); // 改为绿色
            // console.log('同步成功:', reslut);
          })
          .catch(error => {
            // 上传失败处理
            console.error('上传MES失败:', error);
            this.$message.error('上传MES失败: ' + error.message);
            this.changeButtonType('primary'); // 恢复原色
          })
          .finally(() => {
            // 无论成功失败都关闭loading
            loadingInstance.close();
          });

        } else if (this.boxButtons[0].type == "warning") {
          alert("请等待上传MES！！！");
        }
      }
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      console.log("??????????//",formData)
      return true;
    },
    delBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
   addAfter(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      //添加后刷新字典
      
      return true;
    },
    updateAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      this.changeButtonType('primary'); // 恢复原色
      
      return true;
    },
    delAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典      
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=="Add";
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段="xxx";
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    }
  }
};
export default extension;
